<script setup lang="ts">
import { captchaVerify } from '@/api';
import { useSliderCaptcha } from './composables';
import type { SliderCaptchaEmits } from './types';
import {
  EMITS_SLIDERCAPTCHA_CLOSE,
  EMITS_SLIDERCAPTCHA_SUCCESS
} from '@/constants/events';

const id = 'captchaRef' + Math.random();

const emits = defineEmits<SliderCaptchaEmits>();

const { captcha } = useSliderCaptcha({ domId: id, onSuccess, onFail });

async function onSuccess(arr: any[]) {
  const res = await captchaVerify({ behavior: arr });
  if (res) {
    emits(EMITS_SLIDERCAPTCHA_SUCCESS);
  }
}

function onFail() {
  console.log('onFail');
}

const onReset = () => {
  (captcha.value as any).reset();
};

const onClose = () => {
  emits(EMITS_SLIDERCAPTCHA_CLOSE);
};
</script>

<template>
  <div
    class="fixed top-[20%] left-[50%] h-[270px] w-[340px] translate-x-[-50%] rounded border border-zinc-200 bg-white text-sm shadow-2xl dark:border-zinc-900 dark:bg-zinc-800"
  >
    <div
      class="mb-1 flex h-5 w-full items-center justify-between px-1 text-left"
    >
      <span class="flex-grow dark:text-zinc-200">请完成验证</span>
      <span class="flex items-center">
        <MSvgIcon
          name="refresh"
          fillClass="fill-zinc-900 dark:fill-zinc-200"
          class="h-3 w-3 cursor-pointer rounded-sm p-0.5 duration-300 hover:bg-zinc-200 dark:hover:bg-zinc-900"
          @click="onReset"
        />
        <MSvgIcon
          name="close"
          fillClass="fill-zinc-900 dark:fill-zinc-200"
          class="h-3 w-3 cursor-pointer rounded-sm p-0.5 duration-300 hover:bg-zinc-200 xl:ml-2 dark:hover:bg-zinc-900"
          @click="onClose"
        />
      </span>
    </div>
    <div :id="id"></div>
  </div>
</template>

<style lang="css" scoped></style>
